﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace LineAndLine
{
	public partial class MainGUI : Form
	{
		/// <summary>
		/// 当前的点
		/// </summary>
		private Point[] points = new Point[4];

		/// <summary>
		/// 当前正在画的点的索引，0开始
		/// </summary>
		private int index = 0;

		/// <summary>
		/// 当前是否正在画点
		/// </summary>
		private bool isDrawing = false;

		/// <summary>
		/// 绘制线段的笔实例
		/// </summary>
		private Pen linePen = new Pen(Color.Blue, 1.5f);

		/// <summary>
		/// 绘制点的笔刷实例
		/// </summary>
		private Brush pointBrush = new SolidBrush(Color.Red);

		/// <summary>
		/// 本窗体画布
		/// </summary>
		private Graphics graphics;

		/// <summary>
		/// 在当前画布上画一个点
		/// </summary>
		/// <param name="point">传入点对象</param>
		private void drawPoint(Point point)
		{
			// 点的直径
			int sideLength = 4;
			// 绘制点中心
			Point center = new Point(point.X - sideLength / 2, point.Y - sideLength / 2);
			Rectangle rectangle = new Rectangle(center, new Size(sideLength, sideLength));
			// 绘制圆点
			graphics.FillEllipse(pointBrush, rectangle);
		}

		/// <summary>
		/// 在当前画布上画一条线
		/// </summary>
		/// <param name="lineSegment">线段</param>
		private void drawLine(LineSegment lineSegment)
		{
			graphics.DrawLine(linePen, lineSegment.Start, lineSegment.End);
		}

		/// <summary>
		/// 判断当前画布上的两个线段的位置关系
		/// </summary>
		private void checkPosition()
		{
			LineSegment line1 = new LineSegment(points[0], points[1]);
			LineSegment line2 = new LineSegment(points[2], points[3]);
			Vector vector1 = new Vector(line1);
			Vector vector2 = new Vector(line2);
			// 平行或者共线判断
			if (vector1.CrossProduct(vector2) == 0)
			{
				if (new Vector(line1.Start, line2.Start).CrossProduct(vector2) == 0)
				{
					result.Text = "两线段共线";
				}
				else
				{
					result.Text = "两线段平行";
				}
			}
			else
			{
				if (!line1.AtSameSide(line2.Start, line2.End) && !line2.AtSameSide(line1.Start, line1.End))
				{
					result.Text = "两线段相交";
				}
				else
				{
					result.Text = "两线段不相交且不平行";
				}
			}
		}

		public MainGUI()
		{
			InitializeComponent();
			graphics = showArea.CreateGraphics();
			graphics.CompositingQuality = CompositingQuality.HighQuality;
			graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
			graphics.SmoothingMode = SmoothingMode.HighQuality;
		}

		private void showArea_MouseClick(object sender, MouseEventArgs e)
		{
			if (isDrawing)
			{
				points[index] = new Point(e.X, e.Y);
				drawPoint(points[index]);
				if (index == 1 || index == 3)
				{
					drawLine(new LineSegment(points[index - 1], points[index]));
				}
				if (index == 3)
				{
					index = 0;
					isDrawing = false;
					ok.Enabled = true;
					checkPosition();
					return;
				}
				index++;
			}
		}

		private void ok_Click(object sender, System.EventArgs e)
		{
			showArea.Refresh();
			isDrawing = true;
			ok.Enabled = false;
			result.Text = "";
		}
	}
}